const cloud = require('wx-server-sdk');

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});

const db = cloud.database();
const _ = cloud.database().command;

exports.main = async (event, context) => {
  const timestamp = event.timestamp
  const option = event.option

  const wxContext = cloud.getWXContext()
  const user = await db.collection("user").where({
    openid:wxContext.OPENID,
  }).get()

  if(user.data.length == 0)
  {
    return {
      code:401,
      data:{},
      msg:"have not login"
   }
  }
  
  if(user.data[0].status != 0)
  {
    return {
      code:401,
		 data:{},
		 msg:"no privilege"
    }
  }

  if(option)
  {
    const result = await db.collection("timeTable").where({timestamp:timestamp}).update({
      data:{
        isOpen:true,
      }
    })
    if(result.stats.updated == 0)
    {
      return {
        code:500,
        data:{},
        errMsg:"fail to updated"
      }
    }
  }
  else
  {
    if(event.message == null)
    {
      return {
        code:400,
        data:{},
        msg:"need a reason"
      }
    }
    const result = await db.collection("timeTable").where({timestamp:timestamp}).update({
      data:{
        isOpen:false,
        message:event.message
      }
    })
    if(result.stats.updated == 0)
    {
      return {
        code:500,
        data:{},
        errMsg:"fail to updated"
      }
    }
  }

  return {
    code:200,
    data:{},
    msg:"success"
  }
  

};
